package o2o.web.actions.user;

import o2o.config.dao.UserDaoSql;
import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.JYMathDoubleUtils;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.wallet.UserWalletMemory;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.order.ORDER_STATUS;
import o2o.dao.PO.order.OrderInfo;
import o2o.dao.PO.user.UserDataManagerPO;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.wallet.UserWallet;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Controller
public class UserDataManagerAction {


    @RequestMapping(method = RequestMethod.POST, value = "/admin/user/data")
    @ResponseBody
    public String userDataManager(Integer page, Integer size,
                                  String role,     //   role 作为倒序 正序
                                  String mess) {   //  mess 作为排序内容

        /*  page = (page - 1) * size;

        List<UserDataManagerPO> userDataManagerPOList = getUserData(page, size);


        //  进行排序
        if (userDataManagerPOList.size() > 0) {
            toSortForList(userDataManagerPOList, role, mess);
        }       */

        List<UserInfo> list = UserInfoMemory.getInstance().listV2();
        List<UserDataManagerPO> userDataManagerPOList = new ArrayList<>();
        //  累计订单和退单
        List<OrderInfo> userList = getUserCount();
        // 获取充值和消费
        // List<UserWalletFlow> userWalletFlowList = getUserFlow();


        for (UserInfo userInfo : list) {
            UserDataManagerPO userDataManagerPO = new UserDataManagerPO();
            int success = 0;
            int error = 0;
            double chu = 0.0;
            double ru = 0.0;
            for (int i = 0; i < userList.size(); i++) {
                if (userList.get(i).getUsername().equals(userInfo.getUsername())) {
                    userDataManagerPO.setNowIntegral(userList.get(i).getIntegral());
                    if (userList.get(i).getOrderStatus() == ORDER_STATUS.OVER) {
                        success++;
                    }
                    if (userList.get(i).getOrderStatus() == ORDER_STATUS.PAYED_CANCEL) {
                        error++;
                    }
                    if (userList.get(i).getOrderType() == 0) {
                        chu = JYMathDoubleUtils.add(chu, userList.get(i).getTotalPrice());
                    }
                    if (userList.get(i).getOrderType() == 1) {
                        ru = JYMathDoubleUtils.add(ru, userList.get(i).getTotalPrice());
                    }
                    userList.remove(i);
                    i--;
                }
            }

            userDataManagerPO.setCumulativeRecharge(ru);
            userDataManagerPO.setCumulativeConsumption(chu);
            userDataManagerPO.setSuccessCount(success);
            userDataManagerPO.setErrorCount(error);
            userDataManagerPO.setCity(userInfo.getProvince() + userInfo.getCity());      // 城市
            userDataManagerPO.setUsername(userInfo.getUsername());                       // 登陆名
            userDataManagerPO.setSignPhoto(userInfo.getSignPhoto());                     //  头像
            userDataManagerPO.setSex(userInfo.getSex());                                 // 性别
            userDataManagerPO.setName(userInfo.getName());                               // 姓名

            UserWallet wallet = UserWalletMemory.getInstance().getWallet(userInfo.getUsername());
            if (wallet != null) {
                userDataManagerPO.setMoney(wallet.getMoney());
            } else {
                userDataManagerPO.setMoney(0.0);
            }
            userDataManagerPOList.add(userDataManagerPO);
        }
        //  排序
        toSortForList(userDataManagerPOList, role, mess);

        //分页返回
        List<UserDataManagerPO> nowList = new ArrayList<>();
        int totalcount = userDataManagerPOList.size();
        if (userDataManagerPOList.size() > 0) {
            int size2 = page * size;
            while (size2 > userDataManagerPOList.size()) {
                size2--;
            }
            nowList = userDataManagerPOList.subList((page - 1) * size, size2);
        }

        return AjaxResult.successResult(totalcount, nowList.size(), nowList);
    }


    //  获取用户的订单和退单量和充值消费记录
    private List<OrderInfo> getUserCount() {
        List<OrderInfo> orderInfoList = null;
          /*        SELECT u.username,o.orderstatus,u.orderTotalMoney AS totalPrice,u.flowtype AS orderType,IFNULL(s.score,0) AS integral
                FROM user_wallet_flow u LEFT JOIN order_info o ON u.username=o.username AND u.delflag=0
                AND o.delflag=0 AND (o.orderstatus=9 OR o.orderstatus=4)
                LEFT JOIN user_score_flow s ON u.username=s.username AND s.delflag=0 GROUP BY u.orderno

            */
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT u.username,o.orderstatus,u.orderTotalMoney AS totalPrice,u.flowtype AS orderType,IFNULL(s.score,0) AS integral FROM ")
        .append(PojoTables.USER_WALLET_FLOW).append(" u LEFT JOIN ").append(PojoTables.OrderInfo).append(" o ON u.username=o.username AND u.delflag=0 AND o.delflag=0 AND (o.orderstatus=9 OR o.orderstatus=4) LEFT JOIN ")
        .append(PojoTables.USER_SCORE_FLOW).append(" s ON u.username=s.username AND s.delflag=0 GROUP BY u.orderno");
        try {
            orderInfoList = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return orderInfoList;
    }

    //  对集合进行排序
    private void toSortForList(List<UserDataManagerPO> userDataManagerPOList, String role, String mess) {
        // 正序
        if ("1".equals(role)) {
            try {
                Collections.sort(userDataManagerPOList, new Comparator<UserDataManagerPO>() {
                    @Override
                    public int compare(UserDataManagerPO o1, UserDataManagerPO o2) {
                        if ("1".equals(mess)) {
                            return o1.getCumulativeRecharge().compareTo(o2.getCumulativeRecharge());
                        } else if ("2".equals(mess)) {
                            return o1.getCumulativeConsumption().compareTo(o2.getCumulativeConsumption());
                        } else if ("3".equals(mess)) {
                            return 1;
                        } else if ("4".equals(mess)) {
                            return o1.getMoney().compareTo(o2.getMoney());
                        } else if ("5".equals(mess)) {
                            return 1;
                        } else if ("6".equals(mess)) {
                            return o1.getSuccessCount() - o2.getSuccessCount();
                        } else {
                            return o1.getErrorCount() - o2.getErrorCount();
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }

            //  倒叙
        } else if ("2".equals(role)) {
            Collections.sort(userDataManagerPOList, new Comparator<UserDataManagerPO>() {
                @Override
                public int compare(UserDataManagerPO o1, UserDataManagerPO o2) {
                    if ("1".equals(mess)) {
                        return o2.getCumulativeRecharge().compareTo(o1.getCumulativeRecharge());
                    } else if ("2".equals(mess)) {
                        return o2.getCumulativeConsumption().compareTo(o1.getCumulativeConsumption());
                    } else if ("3".equals(mess)) {
                        return 1;
                    } else if ("4".equals(mess)) {
                        return o2.getMoney().compareTo(o1.getMoney());
                    } else if ("5".equals(mess)) {
                        return 1;
                    } else if ("6".equals(mess)) {
                        return o2.getSuccessCount() - o1.getSuccessCount();
                    } else {
                        return o2.getErrorCount() - o1.getErrorCount();
                    }
                }
            });
        }
    }
}
